#include "apue.h"

#include <sys/shm.h>
#include <sys/wait.h>

int main()
{
  int shmid;
  pid_t pid;
  char *ptr;

  // 创建共享存储
  shmid = shmget(IPC_PRIVATE, 128, IPC_CREAT | S_IWUSR | S_IRUSR);
  if (shmid < 0) {
    printf("shmget failed.\n");
  } else {
    printf("shmid=%d\n", shmid);
  }

  if ((pid = fork()) < 0) {
    printf("fork failed.\n");
  } else if (pid > 0) {
    // parent
    // 获取存储区地址
    if ((ptr = shmat(shmid, 0, 0)) == (void *)-1) {
      printf("parent: shmat failed.\n");
    }
    // 写入
    char *str = "abcdefg";
    memcpy(ptr, str, sizeof(str) + 1);

    wait(NULL);
    return 0;
  } else {
    // child
    sleep(1);
    // 获取存储器地址
    if ((ptr = shmat(shmid, 0, 0)) == (void *)-1) {
      printf("child : shmat failed.\n");
    }
    printf("child: %s\n",ptr);

    return 0;
  }

  return 0;
}